package com.tinysoft.gameframework;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class MainView extends SurfaceView implements Callback {

	private MainThread mainThread;
	private Context mainContext;
	private MainActivity mainActivity;
	private boolean updateView;
	private SoundEffect sound;

	public MainView(Context context) {
		super(context);
		getHolder().addCallback(this);
		mainThread = new MainThread(getHolder(), this);
		setFocusable(true);
		mainContext = context;
		
		sound = new SoundEffect(context);
	}
	
	public boolean stopDrawing(boolean trueOrFalse) {
		updateView = !trueOrFalse;
		return updateView;
	}
	
	public boolean startDrawing(boolean trueOrFalse) {
		updateView = trueOrFalse;
		return updateView;
	}
	
	public boolean canDrawing() {
		return updateView;
	}
		
	public void init(int width, int height, MainActivity _mainActivity) {
		mainActivity = _mainActivity;
		updateView = true;
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		mainThread.setRunning(true);
		try {
			if (mainThread.getState() == Thread.State.TERMINATED) {
				mainThread = new MainThread(getHolder(), this);
				mainThread.setRunning(true);
				setFocusable(true);
				mainThread.start();
			}
			else {
				mainThread.start();
			}
		}
		catch (Exception e) {
			Log.i("MainView", e.toString());
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		Log.i("MainView", "surfaceDestory");
		boolean retry = true;
		mainThread.setRunning(false);
		while (retry) {
			try {
				mainThread.join();
				retry = false;
			}
			catch (Exception e) {
				Log.i("MainView", "surfaceDestroyed " + e.toString());
			}
		}
	}
	
	@Override
	public void onDraw(Canvas canvas) {
		if (canDrawing() == false) {
			return;
		}
		
	
		Paint backPaint = new Paint();
		
		canvas.drawColor(Color.BLUE);
		backPaint.setColor(Color.rgb(0,100,0));
		int c_width = canvas.getWidth();
		int c_height = canvas.getHeight();
		canvas.drawRect(0,  0, c_width, c_height, backPaint);
		backPaint.setColor(Color.rgb(255,255,255));
		
		int c_startx = (int)(c_width*10/100);
		int c_starty = (int)(c_height*10/100);
		int c_stopx = (int)(c_width*90/100);
		int c_stopy = (int)(c_height*90/100);
		canvas.drawRect(c_startx, c_starty, c_stopx, c_stopy, backPaint);
		backPaint.setColor(Color.rgb(0,0,255));
		backPaint.setTextSize(20);
		canvas.drawText("SurfaceView!!",  (int)(c_width*30/100),  (int)(c_height*30/100), backPaint);
	}
}
